<!-- 维护UI和逻辑层的关系 -->
<template>
  <div v-if="modalsWithVisibility.length">
    <GenericModal
      v-for="modal in modalsWithVisibility"
      :key="modal.id"
      v-model="modal.visible"
      :animation-type="modal.options?.animationType"
      :position="modal.options?.position"
      :show-overlay="modal.options?.showOverlay"
      :overlay-color="modal.options?.overlayColor"
      :close-on-click-overlay="modal.options?.closeOnClickOverlay"
      :duration="modal.options?.duration"  
      @update:modelValue="handleClose(modal.id, $event)"
    >
      <component :is="modal.component" v-bind="modal.props" @close="() => handleClose(modal.id, false)" />
    </GenericModal>
  </div>
</template> 

<script setup lang="ts">
import { computed, reactive, watch } from 'vue'
import { useModalStore } from '@/store/modules/modal'
import GenericModal from '../GenericModal.vue'

const modalStore = useModalStore()

// 创建一个响应式对象来追踪每个弹框的可见性
// 这是因为 v-model 不能直接绑定到 Pinia store 的数组项上
const modalVisibility = reactive<Record<string, boolean>>({})

// 监听 store 中 modals 数组的变化
watch(
  () => modalStore.modals,
  (newModals) => {
    // 为新弹框设置可见性为 true
    newModals.forEach(modal => {
      if (modalVisibility[modal.id] === undefined) {
        modalVisibility[modal.id] = true
      }
    });
    // (可选) 清理已不存在的弹框的可见性状态
    Object.keys(modalVisibility).forEach(id => {
      if (!newModals.some(m => m.id === id)) {
        delete modalVisibility[id]
      }
    })
  },
  { deep: true, immediate: true }
)

// 将响应式状态映射到 v-for 的模板中
const modalsWithVisibility = computed(() => 
  modalStore.modals.map(modal => ({
    ...modal,
    visible: modalVisibility[modal.id] ?? false
  }))
)

// 当弹框关闭时（例如点击遮罩层），更新状态并从 store 中移除
const handleClose = (id: string, isVisible: boolean) => {
  if (!isVisible) {
    modalVisibility[id] = false
    // 等待动画结束后再从 store 中移除，避免闪烁
    setTimeout(() => {
      modalStore.hide(id)
    }, 300) // 动画时长
  }
}
</script>

